"""
连接数据库的框架方法
"""
from pymysql.constants import CLIENT

from utils.log_util import logger
from utils.read import base_data
import pymysql

data = base_data.read_ini()['mysql']  # 获取到ini中的mysql数据库信息
# 拿到myslq信息后进行数据组装
BD_CONF = {
    "host": data['MYSQL_HOST'],
    "port": int(data['MYSQL_PORT']),
    "user": data['MYSQL_USER'],
    "password": data['MYSQL_PASSED'],
    "db": data['MYSQL_DB']

}


class MysqlDb:
    def __init__(self):
        # MYSQL连接

        self.conn = pymysql.connect(**BD_CONF)  # 建立连接
        self.cur = self.conn.cursor(cursor=pymysql.cursors.DictCursor)  # 打开游标

    def __del__(self):
        self.cur.close()  # 关闭连接
        self.conn.close()  # 关闭游标

    # 查询多条
    def select_db_all(self, sql):

        logger.info('执行sql:{0}'.format(sql))
        self.cur.execute(sql)  # 执行sql
        result = self.cur.fetchall()
        logger.info("执行的结果{0}".format(result))
        return result  # 获取数据

    # 查询1条数据，就不是数组了 不需要加下标
    def select_db_one(self, sql):
        logger.info('执行sql:{0}'.format(sql))
        self.cur.execute(sql)  # 执行sql
        result = self.cur.fetchone()  # 获取数据
        logger.info("执行的结果{0}".format(result))
        return result

    def execute_db(self, sql):  # 更新数据
        try:
            logger.info('执行sql:{0}'.format(sql))
            self.cur.execute(sql)
            self.conn.commit()
        except Exception as e:
            logger.info("执行sql出错了{0}".format(e))


db = MysqlDb()

if __name__ == '__main__':
    db = MysqlDb()
    # result1 = db.select_db_one('SELECT code FROM users_verifycode WHERE mobile="18339914656" order by id desc')
    # # print(result1['code'])  # 数组里面取值应该带上序号
    # result12 = db.select_db_all('SELECT code FROM users_verifycode WHERE mobile="18339914656" order by id desc')
    # print(result12[0]['code']) #查询多条下面要加上下标
